<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2021/07/20
 * Time: 18:15
 * @link http://www.lmterp.cn
 */

namespace app\common\service\import;

use app\common\library\Tools;
use app\common\model\ProductKeyword;
use app\common\model\ProductKeywordCategory;
use app\common\service\product\ProductService;

/**
 * 导入关键词
 * Class Keyword
 * @package app\common\service\import
 */
class Keyword extends BaseImport
{

    /**
     * 表格头信息
     * @var array
     */
    protected $header = [];

    /**
     * 源表格头信息
     * @var array
     */
    protected $eheader = [];

    public function init()
    {
        $this->header = [
            '关键词' => 'word',
            '分类' => 'cate_id',
            '关键词热度' => 'hot',
            '备注' => 'remark',
        ];
        $this->eheader = array_flip($this->header);
    }

    protected function write()
    {
        $userId = Tools::isCli() ? 0 : session("lmterp")->id;
        $service = ProductService::getInstance();
        foreach($this->getData() as $item)
        {
            $insert = $service->addKeyword($item + ["create_by" => $userId]);
        }
        return true;
    }

    protected function validate(&$row = [], $key = 0)
    {
        $row = Tools::replaceArrayKey($this->header, $row);
        $error = [];
        $reqField = ['word', 'cate_id'];
        if(($req = $this->requireField($row, $reqField, $this->eheader)) !== true) $error = array_merge($error, $req);
        if(Tools::contains($row['cate_id'], '>'))
        {
            if(!ProductKeywordCategory::hasMoreName($row['cate_id'], $cateId)) $error[] = "分类【{$row['cate_id']}】有误，请检查";
            $row['cate_id'] = $cateId;
        }
        else
        {
            if(!ProductKeywordCategory::hasName($row['cate_id'])) $error[] = "分类【{$row['cate_id']}】不存在，请检查";
            else $row['cate_id'] = ProductKeywordCategory::get(['name' => trim($row['cate_id'])])->cate_id;
        }
        if(ProductKeyword::hasWord($row['word'], $row['cate_id'])) $error[] = "关键词【{$row['word']}】已存在";
        $hot = intval($row['hot']);
        if($hot < 1 || $hot > 5) $hot = 1;
        $row['hot'] = $hot;
        if(!empty($error)) return join(", ", $error);
        return true;
    }

    protected function transform(&$row = [])
    {

    }
}